package com.zhdl.websocket.custom.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @author: liu zhenming
 * @date: 2023/8/18 16:31
 */
@Slf4j
@Component
@ServerEndpoint(value = "/custom/{clientId}")
public class CustomWsServer {

    public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    public static void pushCustomMsg(String clientId, String msg) {

        Session session = sessionMap.get(clientId);

        if (session != null && session.isOpen()) {
            session.getAsyncRemote().sendText("CustomWsServer WebSocket: " + msg);
        } else {

            log.error("客户端 {} sessionId 已关闭", clientId);
        }

    }

    @OnOpen
    public void onOpen(Session session, @PathParam("clientId") String clientId) {
        // WebSocket 连接建立时调用
        log.info("CustomWsServer WebSocket connection opened: {} , 链接的客户端id: {}", session.getId(), clientId);
        //保存session对照关系
        //之后也可以自己用redis等方式实现
        sessionMap.put(clientId, session);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 接收到客户端发送的消息时调用
        log.info("CustomWsServer WebSocket connection onMessage: id: {} Received message: {}", session.getId(), message);
        // 回复消息给客户端
        session.getAsyncRemote().sendText("WebSocket Received: " + message);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        //客户端关闭时调用
        log.info("CustomWsServer WebSocket connection onClose: " + session.getId());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        //客户端异常时调用
        log.error("CustomWsServer ws : onError id: {} throwable : [{}]", session.getId(), throwable.getMessage());
    }
}
